<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class User extends MY_Main {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -  
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in 
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
	
	public function index()
	{						
		$this->load->view('template/header');
		$this->load->view('user/main');
		//$this->load->view('template/footer');
	}
	
	public function createUser(){
		$data["title"]  = "Add User";
		$data["action"] = "add";
		
		$this->load->view('template/header');
		$this->load->view('user/form',$data);
		$this->load->view('template/footer');
	}
	
	public function doCreate(){
		$this->load->model ('master/users','user');
		
		$key = config_item('encryption_key');
		
		$loginname = $_POST['login_name'];
		$password = md5($_POST['password'].$key);
		$name = $_POST['name'];
		$surname = $_POST['surname'];
		$email = $_POST['email'];
		$role = $_POST['role'];
		$enabled = isset($_POST['user_enabled'])?$_POST['user_enabled']:0;
		$this->user->create_user($loginname,$password,$name,$surname,$email,$role,$enabled);
		
	}
	
	public function editUser(){
		$this->load->model ('master/users','user');
		
		$userid = $_GET['userid'];
							
		$data["user"] = $this->user->get_user($userid);
		//$data["companyid"] = $companyid;
		$data["title"]  = "Edit User";
		$data["action"] = "edit";
		
		$this->load->view('template/header');
		$this->load->view('user/form',$data);
		$this->load->view('template/footer');
	}
	
	public function doEdit(){
		$this->load->model ('master/users','user');
	
		$userid = $_POST['user_id'];
		$loginname = $_POST['login_name'];
		$password = $_POST['password'];
		
		if ($password != ""){
			$key = config_item('encryption_key');
			$password = md5($password.$key);
		}
		
		$name = $_POST['name'];
		$surname = $_POST['surname'];
		$email = $_POST['email'];
		$role = $_POST['role'];
		$enabled = isset($_POST['user_enabled'])?$_POST['user_enabled']:0;
		$this->user->edit_user($userid,$password,$name,$surname,$email,$role,$enabled);
				
	}
	
	public function doDelete(){
		$this->load->model ('master/users','user');
	
		$userid = $_POST['userid'];
		$this->user->delete_user($userid);
	
	}
	
	
	public function getalluser(){
	
		$this->load->model ('master/users','user');
		
		$data = $this->user->getAllUser();
	
		header("Content-type: application/json");
		echo "{\"data\":" .json_encode($data). "}";
		
	}
	
}